package com.zzyl.common.ai;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzyl.common.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AIModelInvoker {
    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();

    @Autowired
    private BaiduAIProperties baiduAIProperties;

    public String qianfanInvoker(String prompt) {
        // 打印 prompt
        log.info("AI模型调用的prompt: {}", prompt);

        // 构造 message 对象
        String jsonBody = getJsonBody(prompt);

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        Request request = new Request.Builder()
                .url("https://qianfan.baidubce.com/v2/chat/completions")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("appid", baiduAIProperties.getAppId())
                .addHeader("Authorization", "Bearer " + baiduAIProperties.getAppKey())
                .build();
        Response response = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
            String responseBody = response.body().string();
            //System.out.println("原始接口返回: " + responseBody);
            // 解析 JSON
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(responseBody);
            // 取到 content 字段
            String content = root.path("choices").get(0)
                    .path("message").path("content").asText();

            // 去掉 markdown 的 ```json 和 ``` 标记
            String innerJson = content
                    .replaceAll("(?s)```json\\s*", "")
                    .replaceAll("(?s)```", "")
                    .trim();

            // 清理可能的注释后再解析
            String cleanedJson = innerJson.replaceAll("//.*|/\\*(.|[\\r\\n])*?\\*/", "");
            // 再解析成 JSON 对象
            JsonNode result = mapper.readTree(cleanedJson);
            log.info("老人体检报告Ai总结的JSON内容: {}", result);
            return result.toString();
        } catch (IOException e) {
            throw new BaseException("AI模型分析错误,请重试!");
        }
    }

    /**
     * 获取请求的JSON
     *
     * @param prompt
     * @return
     */
    private String getJsonBody(String prompt) {
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", prompt);
        // 会自动转义换行和引号
        JSONArray messages = new JSONArray();
        messages.add(message);

        // 构造请求 JSON
        JSONObject requestJson = new JSONObject();
        requestJson.put("model", baiduAIProperties.getQianfanModel());
        requestJson.put("messages", messages);

        // 转成字符串
        String jsonBody = requestJson.toJSONString();
        return jsonBody;
    }
}